package MyBlog.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import MyBlog.dao.UserDao;
import MyBlog.entity.User;

@Repository("userDao")
public class UserDaoImpl implements UserDao {
	
	@Autowired
	private HibernateTemplate hibernateTemplate;

	public List<User> getUserByVisitTimes(final int pageSize) {
		return hibernateTemplate.execute(new HibernateCallback<List<User>>() {
			public List<User> doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria cri = session.createCriteria(User.class);
				cri.addOrder(Order.desc("visitTimes"));
				return cri.setFirstResult(0).setMaxResults(pageSize).list();
			}
		});
	}
	
	public static void main(String[] args) {
		ApplicationContext atx = new ClassPathXmlApplicationContext("beans.xml");
		UserDao userDao = (UserDao) atx.getBean("userDao");
		System.out.println(userDao.fetchUserById(1).getNickname());
	}

	@Override
	public User checkLogin(String username, String password) {
		List<User> list = (List<User>) hibernateTemplate.find("from User where username=? and password=?",username,password);
		return list.size()==0?null:list.get(0);
	}

	@Override
	public User fetchUserById(int id) {
		return hibernateTemplate.get(User.class, id);
	}

	@Override
	public void update(User user) {
		hibernateTemplate.update(user);
	}

}
